var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd hh:mm:ss';


function padding(s, len) {
  var len = len - (s + '').length;
  for (var i = 0; i < len; i++) {
    s = '0' + s;
  }
  return s;
};

export default {

  //时间格式转时间字符串“yyyy-MM-dd hh:mm:ss”，使用：this.$util.timeStr(new Date(), "yyyy-MM-dd hh:mm:ss")
  timeStr: function (date, pattern) {
    if (!date) {
      return ""
    }
    pattern = pattern || DEFAULT_PATTERN;
    return pattern.replace(SIGN_REGEXP, function ($0) {
      switch ($0.charAt(0)) {
        case 'y':
          return padding(date.getFullYear(), $0.length);
        case 'M':
          return padding(date.getMonth() + 1, $0.length);
        case 'd':
          return padding(date.getDate(), $0.length);
        case 'w':
          return date.getDay() + 1;
        case 'h':
          return padding(date.getHours(), $0.length);
        case 'm':
          return padding(date.getMinutes(), $0.length);
        case 's':
          return padding(date.getSeconds(), $0.length);
      }
    });
  },



  //新标签打开路由，使用：this.$util.newpage(this,'user',{id:1,type:2})
  newpage: function (that, page, query) {
    let newpage = that.$router.resolve({
      name: page,
      query: query
    })
    window.open(newpage.href, '_blank');
  },



  //新标签打开外链，使用：this.$util.openUrl("http://www.baidu.com")
  openUrl: function (url) {
    window.open(url, '_blank');
  },



  //数组转换成树形结构，需要转换的数组data，主键默认id，父级id默认parent_id，子数组默认childrens，使用：this.$util.translateDataToTree(data,'id', 'parent_id', 'children');
  translateDataToTree: function (data, id, parent_id, children) {
    id = id || 'id';
    parent_id = parent_id || 'parent_id';
    children = children || 'children';

    let parents = data.filter(value => value[parent_id] == 'undefined' || value[parent_id] == null || value[parent_id] == 0)
    let childrens = data.filter(value => value[parent_id] !== 'undefined' && value[parent_id] != null && value[parent_id] != 0)
    let translator = (parents, childrens) => {
      parents.forEach((parent) => {
        // parent[children] = []
        childrens.forEach((current, index) => {
          if (current[parent_id] === parent[id]) {
            let temp = JSON.parse(JSON.stringify(childrens))
            temp.splice(index, 1)
            translator([current], temp)
            typeof parent[children] !== 'undefined' ? parent[children].push(current) : parent[children] = [
              current
            ]
          }
        })
      })
    }
    translator(parents, childrens)
    return parents
  },



  // 遍历树形结构取最后一级组成的数组，使用：this.$util.forLastTree(data);
  forLastTree: function (data, lastchildren) {
    lastchildren = lastchildren || [];
    for (let i = 0; i < data.length; i++) {
      let chlist = data[i];
      if (chlist.children !== undefined && chlist.children.length > 0) {
        this.forLastTree(chlist.children, lastchildren);
      } else {
        lastchildren.push(chlist);
      }
    }
    return lastchildren
  },

  // 转换日期范围格式2019年04月05日 - 06日，使用：this.$util.timeStrRange(start,end);
  timeStrRange: function (startStr, endStr) {
    startStr = startStr || null;
    endStr = endStr || null;
    let startYear = padding(new Date(startStr).getFullYear(), 4)
    let startMonth = padding(new Date(startStr).getMonth() + 1, 2)
    let startDate = padding(new Date(startStr).getDate(), 2)

    let endYear = padding(new Date(endStr).getFullYear(), 4)
    let endMonth = padding(new Date(endStr).getMonth() + 1, 2)
    let endDate = padding(new Date(endStr).getDate(), 2)

    if (new Date(startStr).getFullYear() != new Date(endStr).getFullYear()) {
      return startYear + "年" + startMonth + "月" + startDate + "日" + "-" + endYear + "年" + endMonth + "月" + endDate + "日"
    } else if (new Date(startStr).getMonth() != new Date(endStr).getMonth()) {
      return startYear + "年" + startMonth + "月" + startDate + "日" + "-" + endMonth + "月" + endDate + "日"
    } else if (new Date(startStr).getDate() != new Date(endStr).getDate()) {
      return startYear + "年" + startMonth + "月" + startDate + "日" + "-" + endDate + "日"
    } else {
      return startYear + "年" + startMonth + "月" + startDate + "日"
    }
  },

  //  转 年-月-日
  timeStr2: function (str) {
    str = new Date(str);
    let year = str.getFullYear() + '年';
    let month = str.getMonth() + 1 + '月';
    let date = str.getDate() + '日';
    return year + month + date
  },


  // 数组根据某个关键字分组，arr需要分组的数组，id关键字默认id，other分组除关键字(id)组成的其他字段（用“-”拼接），使用：this.$util.arrGrouping(arr,id,other);
  arrGrouping: function (arr, id, other) {
    arr = arr || [];
    id = id || 'id';
    other = other || '';

    if (other) {
      other = other.split("-")
    } else {
      other = []
    }
    let map = {},
      dest = [];
    for (let i = 0; i < arr.length; i++) {
      let ai = arr[i];
      if (!map[ai[id]]) {
        let obj = {
          [id]: ai[id],
          list: [ai]
        }
        for (const i of other) {
          obj[i] = ai[i]
        }
        dest.push(obj);
        map[ai[id]] = ai;
      } else {
        for (let j = 0; j < dest.length; j++) {
          let dj = dest[j];
          if (dj[id] == ai[id]) {
            dj.list.push(ai);
            break;
          }
        }
      }
    }
    return dest

  },

  //产生任意长度随机字母数字组合,randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位,使用：this.$util.randomWord(randomFlag,min,max);
  randomWord(randomFlag, min, max) {
    var str = "",
      range = min,
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (randomFlag) {
      range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
      let pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  },

  // 格式化时间 如: 2021-04-24T04:58:44.000Z
  formDate(date) {
    let json_date = new Date(date).toJSON();
    return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
  },

  // 数字转中文
  toChineseNum(num) {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    let unit = ['', '十', '百', '千', '万', '亿'];
    num = parseInt(num);
    let getWan = (temp) => {
      let strArr = temp.toString().split('').reverse();
      let newNum = '';
      for (var i = 0; i < strArr.length; i++) {
        newNum =
          (i == 0 && strArr[i] == 0
            ? ''
            : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0
              ? ''
              : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) +
          newNum;
      }
      return newNum;
    };
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    if (noWan.toString().length < 4) {
      noWan = '0' + noWan;
    }
    return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
  },

  // 数字转中文
  toNumber(v) {
    let chnNumChar = {
      '零': 0,
      '一': 1,
      '二': 2,
      '三': 3,
      '四': 4,
      '五': 5,
      '六': 6,
      '七': 7,
      '八': 8,
      '九': 9
    };
    for(let k in chnNumChar){
      // console.log(k)
      if(k == v){
        return chnNumChar[k]
      }
    }
  }
};
